package com.handsome.utils;

import com.handsome.config.Constants;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @Author Handsome
 * @Date 2022/2/16 8:41
 * @Version 1.0
 */
@SuppressWarnings({"all"})
public class CreateDestFileNameUtil {
    private volatile static CreateDestFileNameUtil createDestFileUtil;

    private CreateDestFileNameUtil() {
    }

    public static CreateDestFileNameUtil getCreateDestFileUtil() {
        if (createDestFileUtil == null) {
            synchronized (CreateDestFileNameUtil.class) {
                if (createDestFileUtil == null) {
                    createDestFileUtil = new CreateDestFileNameUtil();
                }
            }
        }
        return createDestFileUtil;
    }

    public Map<String, Object> getDestFile(String fileName) {
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 生成文件名称通用方法
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        Random r = new Random();
        StringBuilder tempName = new StringBuilder();
        tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
        String newFileName = tempName.toString();
        // 根据相对路径获取文件夹绝对路径
        String realPath = new File(Constants.FILE_UPLOAD_DIC).getAbsolutePath();
        // 创建文件夹
        File fileDirectory = new File(realPath);
        if (!fileDirectory.exists()) {
            fileDirectory.mkdirs();
        }
        // 获取文件路径
        String filepath = new File(realPath + "//" + newFileName).getAbsolutePath();
        //创建文件
        File destFile = new File(filepath);
        Map<String, Object> map = new HashMap();
        map.put("destFile", destFile);
        map.put("newFileName", newFileName);
        return map;
    }
}
